package com.huobao.yunying.adapters;

import java.util.List;
import java.util.Map;

import org.simple.eventbus.EventBus;
import org.xutils.common.util.LogUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huobao.yunying.activitys.Act_Select_GuigeAndNum;
import com.huobao.yunying.activitys_store.Act_Store;
import com.huobao.yunying.entity.Detailprice_intervals;
import com.huobao.yunying.entity.GouwucgeGoods;
import com.huobao.yunying.entity.GouwucheList;
import com.huobao.yunying.entity.Gouwuche_spec;
import com.huobao.yunying.entity.Gouwuche_specification;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpConst;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.utils.ImageUtils;
import com.huobao.yunying.utils.SkipUtils;
import com.huobao.yunying.utils.Utils;
import com.huobao.zhangying.R;
import com.xrz.sxm.base.dialog.BaseDialog;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class Adapter_Gouwuche extends BaseExpandableListAdapter {

	private LayoutInflater inflater;
	private Context context;
	private List<GouwucheList> lists;

	public List<GouwucheList> getList() {
		return lists;
	}

	/**
	 * 显示总价格的TextView
	 */
	private TextView m_tv_AllPrice;

	private TextView btn_jiesuan;

	public Adapter_Gouwuche(Context context, List<GouwucheList> lists, TextView tv_AllPrice, TextView btn_jiesuan) {
		this.context = context;
		this.lists = lists;
		this.m_tv_AllPrice = tv_AllPrice;
		inflater = LayoutInflater.from(context);
		this.btn_jiesuan = btn_jiesuan;
	}

	@Override
	public int getGroupCount() {
		return lists.size();
	}

	@Override
	public int getChildrenCount(int groupPosition) {
		return lists.get(groupPosition).goods.size();
	}

	@Override
	public Object getGroup(int groupPosition) {
		return null;
	}

	@Override
	public Object getChild(int groupPosition, int childPosition) {
		return null;
	}

	@Override
	public long getGroupId(int groupPosition) {
		return 0;
	}

	@Override
	public long getChildId(int groupPosition, int childPosition) {
		return 0;
	}

	@Override
	public boolean hasStableIds() {
		return true;
	}

	@Override
	public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
		if (convertView == null)
			convertView = inflater.inflate(R.layout.item_gouwuche_group_view, null);
		TextView textView = (TextView) convertView.findViewById(R.id.tv_name);
		textView.setText(lists.get(groupPosition).store_name);
		textView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, Act_Store.class);
				if (lists.get(groupPosition).goods.size() == 0) {
					return;
				}
				intent.putExtra("id", lists.get(groupPosition).goods.get(0).store_id);
				context.startActivity(intent);
			}
		});
		return convertView;
	}

	@Override
	public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView,
							 ViewGroup parent) {
		if (convertView == null)
			convertView = inflater.inflate(R.layout.item_gouwuche_child_view, null);
		CheckBox checkbox = (CheckBox) convertView.findViewById(R.id.checkbox);
		// 上架logo
		ImageView imageview = (ImageView) convertView.findViewById(R.id.imageview);
		// 商品名字
		TextView tv_goods_name = (TextView) convertView.findViewById(R.id.tv_goods_name);
		// 单价
		TextView tv_price = (TextView) convertView.findViewById(R.id.tv_price);
		// 选择多件的时候显示得View
		View llyt_allcount = convertView.findViewById(R.id.llyt_allcount);
		// 一共多少件
		TextView tv_count = (TextView) convertView.findViewById(R.id.tv_count);
		// 规格
		LinearLayout llyt_guige = (LinearLayout) convertView.findViewById(R.id.llyt_guige);

		// 选择单件的显示得View
		View view_dan = convertView.findViewById(R.id.llyt);
		TextView tv_jian = (TextView) convertView.findViewById(R.id.tv_jian);
		final TextView tv_number = (TextView) convertView.findViewById(R.id.tv_number);
		TextView tv_jia = (TextView) convertView.findViewById(R.id.tv_jia);

		// 总价
		TextView tv_allprice = (TextView) convertView.findViewById(R.id.tv_allprice);
		// 删除
		TextView tv_del = (TextView) convertView.findViewById(R.id.tv_del);
		// 编辑
		TextView tv_edit = (TextView) convertView.findViewById(R.id.tv_edit);

		final GouwucgeGoods goods = lists.get(groupPosition).goods.get(childPosition);
		checkbox.setChecked(goods.isSelect);
		ImageUtils.loadimg(imageview, goods.goods_image);
		imageview.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				SkipUtils.seeDetail(context, goods.goods_id, goods.goods_image);
			}
		});
		tv_goods_name.setText(goods.goods_name);
		tv_price.setText("￥" + goods.price);
		if (goods.specification == null || goods.specification.size() == 0) {
			// 单件
			llyt_guige.removeAllViews();
			tv_number.setText(goods.quantity + "");
			llyt_allcount.setVisibility(View.GONE);
			view_dan.setVisibility(View.VISIBLE);
			tv_edit.setVisibility(View.INVISIBLE);
		} else {
			tv_edit.setVisibility(View.VISIBLE);
			llyt_allcount.setVisibility(View.VISIBLE);
			view_dan.setVisibility(View.GONE);
			tv_count.setText(goods.quantity + "");
			showGuige(llyt_guige, goods.specification);
		}
		tv_allprice.setText("￥" + goods.subtotal);
		checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				goods.isSelect = isChecked;
				notifyDataSetChanged();
				setPriceText();
			}
		});
		tv_jian.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int num = Integer.parseInt(tv_number.getText().toString().trim());
				if (checkNum(goods, num) == false) {
					num--;
				} else {
					Toast.makeText(context, "购买数量不能低于起批量", Toast.LENGTH_SHORT).show();
				}
				tv_number.setText("" + num);
				changePrice(goods, num);
			}
		});
		tv_jia.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int num = Integer.parseInt(tv_number.getText().toString().trim());
				num++;
				tv_number.setText("" + num);
				changePrice(goods, num);
			}
		});
		tv_del.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				BaseDialog.TBox("是否要删除？", context, new BaseDialog.OnDialogSelectListener() {
					@Override
					public void onSelect(String input) {
						if (input.equals("true")) {
							del(goods, groupPosition, childPosition);
						}
					}

				});
			}
		});
		tv_edit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, Act_Select_GuigeAndNum.class);
				intent.putExtra("goodsid", goods.goods_id);
				intent.putExtra("gouwucheGoods", goods);
				context.startActivity(intent);
			}
		});
		tv_number.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				int num = Integer.parseInt(tv_number.getText().toString().trim());
				BaseDialog.showEditTextDialog(context, num, goods.stock, new BaseDialog.OnDialogSelectListener() {
					@Override
					public void onSelect(String input) {
						int num = Integer.parseInt(input);
						tv_number.setText("" + num);
						changePrice(goods, num);
					}
				});
			}
		});
		return convertView;
	}

	private void del(GouwucgeGoods goods, final int Groupposition, final int childPosition) {
		Map<String, String> map = HttpUtil.getParams(HttpConst.FRIST_KEY, "cart", "act", "drop", "rec_id",
				goods.rec_id);
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				JSONObject jsonObject = JSON.parseObject(result);
				Toast.makeText(context, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
//				lists.get(Groupposition).goods.remove(childPosition);
//				if(lists.get(Groupposition).goods == null || lists.get(Groupposition).goods.size() == 0){
//					lists.remove(Groupposition);
//					if(lists.size() == 0){
//						EventBus.getDefault().post("", "goFristPage");
//					}
//				}
//				notifyDataSetChanged();
				EventBus.getDefault().post("", "refreshGouwche");
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	/**
	 * 购物车数量改变
	 *
	 * @param goods
	 * @param num
	 */
	private void changeNUMTS(GouwucgeGoods goods, int num) {
		Map<String, String> map = HttpUtil.getParams(HttpConst.FRIST_KEY, "cart", "act", "update", "rec_id",
				goods.rec_id, "id", goods.goods_id, "spec_id", goods.spec_id, "quantity", num + "");
		Http.getInstant().sendRequest(context, map, new HttpListener() {

			@Override
			public void onHttpSuccess(String result) {
				LogUtil.e(result);
			}

			@Override
			public void onHttpError(String error) {

			}
		});
	}

	protected void changePrice(GouwucgeGoods goods, int num) {
		changeNUMTS(goods, num);
		float danjia = Float.parseFloat(goods.price);
		float allPrice = danjia * num;
		goods.subtotal = allPrice;
		goods.quantity = num;
		notifyDataSetChanged();
	}

	private boolean checkNum(GouwucgeGoods goodsData, int num) {
		List<Detailprice_intervals> price_intervals = goodsData.price_intervals;
		int minCount = 0;
		if (price_intervals == null || price_intervals.size() == 0) {
			minCount = 1;
		} else {
			minCount = price_intervals.get(0).min_count;
		}
		return num <= minCount;
	}

	private void setPriceText() {
		boolean isAllNoSelect = true;
		double price = 0;
		for (GouwucheList list : lists) {
			List<GouwucgeGoods> goods = list.goods;
			for (GouwucgeGoods gouwucgeGoods : goods) {
				if (gouwucgeGoods.isSelect) {
					price += gouwucgeGoods.subtotal;
					isAllNoSelect = false;
				}
			}
		}
		m_tv_AllPrice.setText("合计（不含运费）: ￥" + Utils.get2point(price));

		if (isAllNoSelect) {
			btn_jiesuan.setEnabled(false);
		} else {
			btn_jiesuan.setEnabled(true);
		}
	}

	private void showGuige(LinearLayout llyt_guige, List<Gouwuche_specification> specification) {
		llyt_guige.removeAllViews();
		for (int i = 0; i < specification.size(); i++) {
			Gouwuche_specification gouwuche_specification = specification.get(i);
			LinearLayout layout = new LinearLayout(context);
			layout.setOrientation(LinearLayout.HORIZONTAL);
			layout.setGravity(Gravity.CENTER_VERTICAL);
			LayoutParams layoutParams = new LayoutParams(0, LayoutParams.MATCH_PARENT);
			layoutParams.weight = 1;
			layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
			layout.addView(createNameTextView(gouwuche_specification.spec_1), layoutParams);

			layout.addView(createHLine());
			// 生成右边的规格
			LinearLayout linearLayout = new LinearLayout(context);
			linearLayout.setOrientation(LinearLayout.VERTICAL);
			List<Gouwuche_spec> spec = gouwuche_specification.spec;
			for (Gouwuche_spec gouwuche_spec : spec) {
				linearLayout.addView(createValueTextView(
						gouwuche_spec.spec_2 + "		" + gouwuche_spec.num + "*" + gouwuche_spec.price));
				linearLayout.addView(createLine());
			}
			layoutParams = new LayoutParams(0, LayoutParams.WRAP_CONTENT);
			layoutParams.weight = 1;
			layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
			layout.addView(linearLayout, layoutParams);

			llyt_guige.addView(createLine());
			llyt_guige.addView(layout);
		}
	}

	private View createHLine() {
		View view = new View(context);
		view.setLayoutParams(new LayoutParams(1, LayoutParams.MATCH_PARENT));
		view.setBackgroundColor(Color.parseColor("#dddddd"));
		return view;
	}

	private View createLine() {
		View view = new View(context);
		view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 1));
		view.setBackgroundColor(Color.parseColor("#dddddd"));
		return view;
	}

	/**
	 * 生成标题文字
	 *
	 * @param text
	 * @return
	 */
	private TextView createNameTextView(String text) {
		TextView textView = new TextView(context);
		textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		textView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		textView.setText(text);
		textView.setTextSize(16);
//		textView.setPadding(0, 8, 0, 8);
		return textView;
	}

	private TextView createValueTextView(String text) {
		TextView textView = new TextView(context);
		textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		textView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		textView.setText(text);
		textView.setTextSize(14);
		return textView;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		return false;
	}

	@Override
	public boolean areAllItemsEnabled() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void notifyDataSetChanged() {
		super.notifyDataSetChanged();
		setPriceText();
	}
}
